×
☰ See All Chapters

Default Parameter Values in JavaScript ES6 Functions

We can also set default value for a parameter by setting the parameter to the desired value. When default is set then that parameter is optional while calling the function.  If a default value is set then all remaining parameters in list should be set with default value. If there are three parameters and if second parameter is set with default value then third, fourth… parameters also should be set with default value.

function func1( x , y , z = 30 ) {

        return x + y + z;

}

function func2( x , y = 20, z = 30 ) {

        return x + y + z;

}

function func3( x = 10, y = 20, z = 30 ) {

        return x + y + z;

}

func1(10, 20);

func2(10);

func3();

If any middele parameter is set with default value and remaining parameters in the list is not set with default vlaue we get error when that funtion is called with not all parameters.
default-parameter-values-in-javascript-es6-functions-0
 

Old ES5 way to set default params

Approach 1:

function box(height, width, length) {

        var height = height || 50;

        var width = width || 60;

        var length = length || 70;

}

 

It works well, but in the above implementation we didn't account for falsy values. For example: 0, '', null, NaN, false are falsy values.

Approach 2:

function box(height, width, length) {

        var height = typeof height !== 'undefined' ? height : 50;

        var width = typeof width !== 'undefined' ? width : 60;

        var length = typeof length !== 'undefined' ? length : 70;

}

 


All Chapters
Author